#include <iostream>
#include <curl/curl.h>

// 回调函数，用于处理接收到的数据
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    size_t real_size = size * nmemb;
    std::string* response = static_cast<std::string*>(userp);
    response->append(static_cast<char*>(contents), real_size);
    std::cout << real_size << " " << *response << std::endl;
    return real_size;
}

int main() {
    CURL* curl;
    CURLcode res;
    std::string response;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if (curl) {
        // 设置请求的 URL
        curl_easy_setopt(curl, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts/1");
        // 设置回调函数处理接收到的数据
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        // 执行请求
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        } else {
            // 打印响应内容
            std::cout << "Response:\n" << response << std::endl;
        }

        // 清理 curl 对象
        curl_easy_cleanup(curl);
    }

    // 全局清理
    curl_global_cleanup();
    return 0;
}
